package com.hyts.sdkhttp.handler;

import com.alibaba.fastjson.JSONObject;
import com.hyts.sdkhttp.domain.SdkResponse;
import com.hyts.sdkhttp.domain.SdkURLConnection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

/**
 * project-name:iscloud
 * package-name:com.ultrapower.zq.handler
 * author:Libo/Alex
 * create-date:2018-03-12 10:51
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于:
 */
public class SdkResponseHandler {
	
	/**
	 * @throws IOException   
	 * @Title: getResultStr  
	 * @Description: 获取结果信息对象  
	 * @param @param connection
	 * @param @return    参数  
	 * @return SdkResponse    返回类型  
	 * @throws  
	 */ 
	public static SdkResponse getResultStr(final SdkURLConnection connection){
		//建立对象操作
		SdkResponse response = new SdkResponse();
		HttpURLConnection urlConnection = connection.getConnection();
		try(
				InputStream inputStream = urlConnection.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
			) {
			response.setResponseCode(connection.getConnection().getResponseCode());
			if (HttpURLConnection.HTTP_OK == 
					urlConnection.getResponseCode()) {
				response.setSuccess(true);
				StringBuilder sb = new StringBuilder();
				br.lines().forEach(param->{
					sb.append(param);
				});
				response.setResultStr(sb.toString());
			}
			else {
				response.setSuccess(false);
				response.setResultStr(null);
			}
		} catch (IOException e) {
			e.printStackTrace();
			response.setSuccess(false);
			response.setResultStr(null);
		} 
		return response;
	}
	
	
	/**  
	 * @Title: getResultJson  
	 * @Description: 获取结果json集合服务信息  
	 * @param @param connection
	 * @param @return    参数  
	 * @return SdkResponse    返回类型  
	 * @throws  
	 */ 
	public static SdkResponse getResultJson(final SdkURLConnection connection){
		SdkResponse response = getResultStr(connection);
		response.setResultJson(JSONObject.parseObject(response.getResultStr()));
		return response;
	}
	
}
